<template>
  <el-card class="user-info-container">
    <template #header>
      <div class="card-header">
        <h3>基本资料</h3>
      </div>
    </template>

    <el-form ref="form" :model="userInfo" label-width="120px">
      <el-form-item label="用户名">
        <el-input v-model="userInfo.username" disabled />
      </el-form-item>

      <el-form-item label="账户余额">
        <div class="balance-display">
          <el-icon><Wallet /></el-icon>
          <span class="amount">
            ¥ {{ typeof userInfo.money === 'number' ? userInfo.money.toFixed(2) : '加载中...' }}
          </span>
        </div>
      </el-form-item>

      <el-form-item label="邮箱">
        <el-input v-model="userInfo.email" />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="userInfo.phone" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">保存修改</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useUserInfoStore } from '@/stores/userInfo';
import { ElMessage } from 'element-plus';
import { updateUser, getWalletInfo } from '@/api/user';
import { Wallet } from '@element-plus/icons-vue';

const userInfoStore = useUserInfoStore();
const form = ref(null);
const userInfo = ref({
  username: '',
  email: '',
  phone: '',
  money: null
});

onMounted(async () => {
  userInfo.value = { ...userInfoStore.userInfo };

  try {
    const res = await getWalletInfo();
    if (res.code == 200) {
      // 后端返回的 BigDecimal，JSON 化之后就是 number 类型，我们直接用
      userInfo.value.money = res.data;
      // 同时更新 Pinia store
      userInfoStore.setUserInfo({ ...userInfoStore.userInfo, money: res.data });
    } else {
      ElMessage.error(res.message || '获取余额失败');
      userInfo.value.money = 0;
    }
  } catch (error) {
    console.error("获取余额异常:", error);
    ElMessage.error('获取余额请求失败');
    userInfo.value.money = 0;
  }
});

const handleSubmit = async () => {
  if (!form.value) return;

  const dataToUpdate = {
    id: userInfo.value.id,
    email: userInfo.value.email,
    phone: userInfo.value.phone,
  };

  try {
    await updateUser(dataToUpdate);
    ElMessage.success('信息更新成功');
    userInfoStore.setUserInfo({ ...userInfoStore.userInfo, ...dataToUpdate });
  } catch (error) {
    ElMessage.error('更新失败');
  }
};
</script>

<style lang="scss" scoped>
.user-info-container {
  padding: 20px;
}
.balance-display {
  display: flex;
  align-items: center;
  font-size: 1.2em;
  color: var(--el-text-color-primary);

  .el-icon {
    margin-right: 8px;
    color: #E6A23C;
  }

  .amount {
    font-weight: bold;
    font-family: 'Arial', sans-serif;
  }
}
</style>